package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

type Message struct {
	UserId      int    `json:"user_id"`
	ReceiveId   int    `json:"receive_id"`
	MessageType int    `json:"message_type"`
	Cmd         int    `json:"cmd"`
	Content     string `json:"content"`
}
type Node struct {
	Data chan []byte
	conn *websocket.Conn
}

// 用户私聊结构体映射
var UserConn map[int]Node = make(map[int]Node)

func Chat(c *gin.Context) {

	userId, _ := strconv.Atoi(c.Query("user_id"))

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}
	//实例化
	node := Node{
		Data: make(chan []byte, 50),
		conn: conn,
	}
	//结构体映射
	UserConn[userId] = node
	//收发信息
	go read(node)
	go write(node)
}

// 写的是连接连接的 写入的信息
func write(node Node) {
	for {

	}
}

// 读的是连接者的信息
func read(node Node) {
	for {
		_, message, err := node.conn.ReadMessage()
		if err != nil {
			return
		}
		node.Data <- message
	}
}
